// pages/mine/myfavorite/myfavorite.js
Page({
  data: {
    favoriteList: [],
    activeTab: 'festival', // 默认tab
    filteredList: [],
    userId: null, // 登录用户id
    isFavorite: true,
    favoriteId: null
  },

  onShow() {
    // 获取userId
    const userId = wx.getStorageSync('userId');
    this.setData({ userId });
    // 检查是否需要刷新
    if (wx.getStorageSync('refreshFavorite')) {
      this.loadFavoriteList();
      wx.removeStorageSync('refreshFavorite');
    } else if (this.data.favoriteList.length === 0) {
      this.loadFavoriteList();
    } else {
      this.filterList(this.data.activeTab);
    }
  },

  loadFavoriteList() {
    if (!this.data.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    wx.request({
      url: `http://localhost:8080/myfavorites/user/${this.data.userId}`,
      method: 'GET',
      success: (res) => {
        if (res.data.code === 0 || res.data.success) {
          const favoriteList = res.data.data || [];
          // 重点：获取详情
          this.getFavoriteDetails(favoriteList);
        } else {
          wx.showToast({
            title: '获取收藏列表失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.showToast({
          title: '获取收藏列表失败',
          icon: 'none'
        });
      }
    });
  },
  getFavoriteDetails(favoriteList) {
    // 并发请求所有详情
    const promises = favoriteList.map(fav => {
      return new Promise((resolve) => {
        let url = '';
        if (fav.type === 1) {
          url = `http://localhost:8080/news/${fav.typeId}`;
        } else if (fav.type === 2) {
          url = `http://localhost:8080/articles/${fav.typeId}`;
        }
        wx.request({
          url: url,
          method: 'GET',
          success: (res) => {
            if (res.data && res.data.data) {
              resolve({
                ...fav,
                title: res.data.data.title,
                coverImg: res.data.data.coverImg,
                publishTime: res.data.data.publishTime,
                view: res.data.data.view || 0
              });
            } else {
              resolve(fav);
            }
          },
          fail: () => resolve(fav)
        });
      });
    });
  
    Promise.all(promises).then(results => {
      this.setData({
        favoriteList: results
      });
      this.filterList(this.data.activeTab);
    });
  },
  switchTab(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({ activeTab: type });
    this.filterList(type);
  },

  filterList(type) {
    // type: 'festival' or 'health'
    const typeNum = type === 'festival' ? 1 : 2;
    const filtered = this.data.favoriteList.filter(item => item.type === typeNum);
    this.setData({ filteredList: filtered });
  },

  goToDetail(e) {
    const id = e.currentTarget.dataset.id;
    const type = e.currentTarget.dataset.type;
    if (type === 1) {
      wx.navigateTo({
        url: `/pages/healthlife/healthdetails/healthdetails?id=${id}`
      });
    } else if (type === 2) {
      wx.navigateTo({
        url: `/pages/healthlife/festivaldetails/festivaldetails?id=${id}`
      });
    }
  },

  cancelFavorite(e) {
    const id = e.currentTarget.dataset.id;
    const type = e.currentTarget.dataset.type;
    if (!this.data.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    wx.request({
      url: `http://localhost:8080/myfavorites/${id}`,
      method: 'DELETE',
      success: (res) => {
        if (res.data.code === 0 || res.data.success) {
          this.setData({
            isFavorite: false,
            favoriteId: null
          });
          wx.setStorageSync('refreshFavorite', true);
          wx.showToast({ title: '已取消收藏', icon: 'none' });
          this.loadFavoriteList();
        } else {
          wx.showToast({
            title: res.data.message || '收藏失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.showToast({
          title: '取消收藏失败',
          icon: 'none'
        });
      }
    });
  }
})